#include "unp.h"


// clear && ./tcpcli < unp.h
int main(int argc, char * argv[]) {
	char *host = "127.0.0.1";
	if (argc >= 2) {
		host = argv[1];
	}

	SA_IN serv_addr;
	int sockfd;

	Signal(SIGPIPE, sig_pipe);

	printf("cli pid=%d\n", getpid());
	sockfd = Socket(AF_INET, SOCK_STREAM, 0);
	bzero((char*)&serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);
	Inet_pton(AF_INET, host, &(serv_addr.sin_addr));
	Connect(sockfd, (SA*)&serv_addr, sizeof(serv_addr));
	str_cli(stdin, sockfd);
	return 0;
}

void str_cli(FILE* fp, int sockfd) {
	char sendline[MAXLINE], recvline[MAXLINE];
	ssize_t n;

	int maxfdp1, stdineof = 0;
	fd_set rset;

	for (;;) {
		FD_ZERO(&rset);
		int fd1 = fileno(fp);
		if (stdineof == 0) {
			FD_SET(fd1, &rset);
		}
		FD_SET(sockfd, &rset);
		maxfdp1 = maxint(fd1, sockfd) + 1;

		select(maxfdp1, &rset, NULL, NULL, NULL);

		if (FD_ISSET(fd1, &rset)) { // readable
			if (Fgets(sendline, MAXLINE, fp) != NULL) {
				Write(sockfd, sendline, strlen(sendline));
			} else {
				// sleep(10);
				// exit(0);
				shutdown(sockfd, SHUT_WR);
				FD_CLR(fd1, &rset);
				stdineof = 1;
			}
		}

		if (FD_ISSET(sockfd, &rset)) {
			n = readline(sockfd, recvline, MAXLINE);
			if (n == 0) {
				if (stdineof == 1) {
					printf("normaly exit\n");
					return; //normaly exit;
				}
				printf("server close prematurely\n");
				exit(1);
			} else {
				Fputs(recvline, stdout);
			}
		}
	}
}
